<template>
  <div class="app-container">
    <SearchFilter size="medium" :maxShow="3" @search="handleQuery" @reset="resetQuery">
      <el-form :model="queryParams" label-position="right" label-width="70px" ref="queryForm">
        <el-row  :gutter="20">
          <el-col :span="7">
            <el-form-item label="片区名称" prop="areaName">
              <el-input
                v-model="queryParams.areaName"
                placeholder="请输入片区名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="负责人" prop="principal">
              <el-input
                v-model="queryParams.principal"
                placeholder="请输入负责人"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="所属项目" prop="principal">
              <el-input
                v-model="queryParams.principal"
                placeholder="请输入负责人"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </SearchFilter>

    <div class="content-container">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5">
          <p class="header-title">片区列表</p>
        </el-col>
        <div>
          <el-col :span="1.5" v-if="ids.length">
            <el-button
              size="small"
              v-hasPermi="['resource:area:remove']"
              @click="handleDelete"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              v-hasPermi="['resource:area:add']"
            >新增片区</el-button>
          </el-col>
        </div>
      </el-row>
  
      <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" min-width="55" align="center" />
        <el-table-column type="index" label="序号" align="center" min-width="120">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="片区名称" align="center"  min-width="120" prop="areaName" />
        <el-table-column label="片区图片" align="center"  min-width="120" prop="areaImg">
          <template slot-scope="scope">
            <img :src="scope.row.areaImg" alt="" v-if="scope.row.areaImg" class="image" />
            <p class="image" v-else></p>
          </template>
        </el-table-column>
        <el-table-column label="所属项目" align="center"  min-width="120" prop="projectName" />
        <el-table-column label="负责人" align="center"  min-width="120" prop="principal" />
        <el-table-column label="负责人联系方式" align="center"  min-width="130" prop="principalPhone" />
        <el-table-column label="项目经理" align="center"  min-width="120" prop="projectManager" />
        <el-table-column label="项目经理联系方式" align="center"  min-width="130" prop="projectManagerPhone" />
        <el-table-column label="备注" align="center"  min-width="120" prop="remark" />
        <!-- <el-table-column label="附件" align="center"  min-width="120" prop="file" /> -->
        <el-table-column label="操作" align="center"  min-width="180" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="getRouterInfo(scope.row)"
              v-hasPermi="['resource:area:edit']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['resource:area:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['resource:area:remove']"
              class="text-danger"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" custom-class="dialog" :visible.sync="open" append-to-body :close-on-click-modal="false" width="740px">
        <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
          <el-row type="flex" justify="space-between">
            <el-col :span="11">
              <el-form-item label="片区名称" prop="areaName">
                <el-input v-model="form.areaName" placeholder="请输入片区名称" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="所属项目" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择所属项目">
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.projectName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="11">
              <el-form-item label="负责人" prop="principal">
                <el-input v-model="form.principal" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="负责人电话" prop="principalPhone">
                <el-input v-model="form.principalPhone" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="11">
              <el-form-item label="项目经理" prop="projectManager">
                <el-select v-model="form.projectManager" placeholder="请输入项目经理" @change="managerChange">
                  <el-option
                    v-for="item in managerList"
                    :key="item.nickName"
                    :label="item.nickName"
                    :value="item.nickName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="项目经理电话" prop="projectManagerPhone">
                <el-input v-model="form.projectManagerPhone" disabled placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="24">
              <el-form-item label="片区图片" prop="areaImg">
                <image-upload v-model="form.areaImg"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-col :span="24">
              <el-form-item label="上传附件" prop="file">
                <file-upload v-model="form.file"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

  </div>
</template>

<script>
import { listArea, getArea, delArea, addArea, updateArea } from "@/api/resource/area";
import { getUserList } from '@/api/menu';
import { listProject } from '@/api/resource/project'
import SearchFilter from '@/components/SearchFile'

export default {
  name: "Area",
  components: { SearchFilter },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 片区信息表格数据
      areaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaName: null,
        areaImg: null,
        projectId: null,
        principal: null,
        principalPhone: null,
        projectManager: null,
        projectManagerPhone: null,
        file: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: '片区名称不能为空', trigger: "blur" }
        ],
        projectId: [
          { required: true, message: '所属项目不能为空', trigger: "blur" }
        ],
        principal: [
          { required: true, message: '负责人不能为空', trigger: "blur" }
        ],
        principalPhone: [
          { required: true, message: '负责人电话不能为空', trigger: "blur" },
          { pattern: /(1[34578]\d{9})$/, message: "请填写正确的手机号码", trigger: "change" }
        ],
        projectManager: [
          { required: true, message: '项目经理不能为空', trigger: "blur" }
        ],
        projectManagerPhone: [
          { required: true, message: '项目经理电话不能为空', trigger: "blur" },
          { pattern: /(1[34578]\d{9})$/, message: "请填写正确的手机号码", trigger: "change" }
        ]
      },
      options: [],
      managerList: []
    };
  },
  created() {
    this.getProjectList();
    this.getUserListHandle()
  },
  methods: {
    async getUserListHandle() {
      const deptCode = this.$store.state.user.user.dept.deptCode
      const roleKey = deptCode.substring(deptCode.length - 4)
      const res = await getUserList({ roleKey: roleKey + '-manager' })
      if (res.data.length) {
        this.managerList = res.data.map(item => {
          return { ...item, userId: item.userId + '' }
        })
      }
    },
    managerChange(e) {
      let obj = this.managerList.find(item => item.nickName === e)
      this.form.projectManagerPhone = obj.phonenumber
    },
    /** 查询片区信息列表 */
    getList() {
      this.loading = true;
      listArea({...this.queryParams, deptId: this.$store.state.user.user.deptId}).then(response => {
        response.rows.forEach(item => {
          if (item.projectId && this.options) {
            item.projectName = this.options && this.options.find(items => items.id === item.projectId).projectName
          }
          if (item.areaImg) {
            item.areaImg = this.baseUrl + item.areaImg
          }
        })
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询项目 */
    getProjectList() {
      listProject({ deptId: this.$store.state.user.user.deptId, pageNum: -1 }).then(res => {
        this.options = res.rows
        this.getList();
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        areaName: null,
        areaImg: null,
        projectId: null,
        createTime: null,
        updateTime: null,
        principal: null,
        principalPhone: null,
        projectManager: null,
        projectManagerPhone: null,
        remark: null,
        file: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加片区信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArea(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改片区信息";
      });
    },
    /** 跳转详情 */
    getRouterInfo({ id }) {
      this.$router.push("/resource/areaQuery/" + id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArea({...this.form, deptId: this.$store.state.user.user.deptId}).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getProjectList();
            });
          } else {
            addArea({ ...this.form, deptId: this.$store.state.user.user.deptId }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getProjectList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除片区信息编号为"' + ids + '"的数据项？').then(function () {
        return delArea(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('resource/area/export', {
        ...this.queryParams
      }, `area_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
  .image {
    width: 60px;
    height: 60px;
    margin: 0;
    object-fit: cover;
  }
</style>
